<?php

defined('IN_XLP') or exit('Access Denied!');

/*
 * 推广任务后台
 */

class taskAction extends commonAction {

    //后台各种参数
    private $starttime;
    private $endtime;
    private $keyword;
    private $page;
    private $limit;

    function __construct() {
        parent::__construct();
        parent::_checkLogin();
        G('path_mod', 2);
        // error_reporting(0);

        $this->page = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $this->limit = ($this->page - 1) * 20;
        $this->starttime = empty($_GET['starttime']) ? null : strtotime($_GET['starttime']);
        $this->endtime = empty($_GET['endtime']) ? null : strtotime($_GET['endtime']);
        $this->keyword = empty($_GET['keyword']) ? null : parent::safeSearch($_GET['keyword']);
    }

    public function index() {
        $where = " AND t.`is_del`<>1 ";
        if (isset($this->keyword)) {
            $where .= " AND t.`task_title` LIKE '%{$this->keyword}%' ";
        }

        $sql = "SELECT t.`id`,t.`reward_total`,t.`reward_left`,t.`time_start`,t.`promotion_time`,
				t.`time_end`,t.`partin_num`,t.`poster_uid`,t.`task_title`,t.`is_show`,
				p.`poster_name`,r.`reward_name`
				FROM __PRE__task t,__PRE__task_poster p,__PRE__task_reward r
				WHERE t.`poster_uid`=p.`uid` AND t.`reward_type`=r.`id`
				$where
				ORDER BY t.`time_add` DESC";

        $sql_page = $sql . " LIMIT {$this->limit},20";
        $task_list = M()->query($sql_page);

        foreach ($task_list as $k => $v) {
            $task_list[$k]['time_start'] = $v['time_start'] ? date('Y-m-d H:i:s', $v['time_start']) : '';
            $task_list[$k]['time_end'] = $v['time_end'] ? date('Y-m-d H:i:s', $v['time_end']) : '';
            if (!$v['is_show']) {
                $task_list[$k]['state'] = '<span class="red">隐藏</span>';
            } else if ($v['time_start'] > TIME) {
                $task_list[$k]['state'] = '尚未开始';
            } else if ($v['time_start'] <= TIME && ($v['time_end'] >= TIME || empty($v['time_end']))) {
                $task_list[$k]['state'] = '正在进行';
            } else if ($v['time_end'] < TIME && !empty($v['time_end'])) {
                $task_list[$k]['state'] = '已经结束';
            }
        }
        // z($task_list);
        $sql_count = "SELECT count(`id`) total FROM __PRE__task t WHERE 1=1 $where";
        $rs = M()->query($sql_count);
        $total = $rs[0]['total'];


        $this->assign('starttime', $this->starttime ? date('Y-m-d H:i:s', $this->starttime) : '');
        $this->assign('endtime', $this->endtime ? date('Y-m-d H:i:s', $this->endtime) : '');
        $this->assign('keyword', $this->keyword);
        $this->assign('page', $this->page);
        $this->assign('total', $total);
        $this->assign('task_list', $task_list);
        $this->display();
    }

    /*
     * 前五个任务排序
     */

    public function sort() {

        if (count($_POST)) {
            $sort = $this->_post('sort');
            foreach ($sort as $k => $v) {
                M('task')->update(
                        array('sort' => $k), array('id' => $v)
                );
            }
            $this->JsonReturn('ok', null, 1);
        }

        $time = TIME;
        $task_list = M('task')
                ->field('`id`,`task_title`,`time_end`')
                ->where("`time_start`<={$time} AND `is_show`=1 AND `is_del`<>1")
                ->order('`sort`,`time_add` DESC')
                ->findAll();

        $temp_arr = array();
        foreach ($task_list as $k => $v) {
            $task_list[$k]['time_end'] = empty($v['time_end']) ? '' : date('Y-m-d H:i:s', $v['time_end']);
            if ($v['time_end'] && $v['time_end'] > TIME || empty($v['time_end'])) { //即将开始或正在进行
                $task_list[$k]['state'] = 'online';
            } else { //已经结束
                $task_list[$k]['state'] = 'offline';
                $temp_arr[] = $task_list[$k];
                unset($task_list[$k]);
            }
        }
        // $task_list = array_merge($task_list, $temp_arr);
        $task_list = array_slice($task_list, 0, 5);
        // z($task_list);
        $this->assign('task_list', $task_list);
        $this->display();
    }

    /*
     * 添加任务
     */

    public function add() {
        if (count($_POST)) {
            $data = $this->_input();
            //剩余数量等于总数
            $data['reward_left'] = $data['reward_total'];
            //添加时间
            $data['time_add'] = TIME;
            //新增奖品类型
            if ($data['reward_type'] == '-1') {
                $rs = D('task')->addNewReward($data['poster_uid'], $this->_post('reward_name'));
                if ($rs === -1) {
                    $this->JsonReturn('新增奖品名称重复', null, 0);
                } else if (!$rs) {
                    $this->JsonReturn('新增奖品失败', null, 0);
                }
                $data['reward_type'] = $rs;
            }
            //新增任务
            $rs = M('task')->insert($data);
            if ($rs !== false) {
                M('task_poster')->update(
                        "`task_num`=`task_num`+1", array('uid' => $data['poster_uid'])
                );
                $this->JsonReturn('添加任务成功', null, 1);
            } else {
                $this->JsonReturn('添加任务失败', null, 0);
            }
        }

        $uid = $this->_getid('uid');
        //检查用户
        $rs = M('task_poster')
                ->field('`uid`')
                ->where(array('uid' => $uid))
                ->find();
        if (!$rs) {
            showError('参数错误');
        }
        //获取发布人奖品类型
        $reward = D('task')->getReward($uid);
        $this->assign('reward', $reward);
        $this->assign('poster_uid', $uid);
        $this->display();
    }

    /*
     * 编辑任务
     */

    public function edit() {

        if (count($_POST)) {
            $data = $this->_input();
            $task_id = $this->_postid('task_id');
            $rs = M('task')->update(
                    $data, array('id' => $task_id)
            );
            $this->JsonReturn('编辑任务成功', null, 1);
        }

        $task_id = $this->_getid('id');
        $task = M('task')->where(array('id' => $task_id))->find();
        if (!$task) {
            showError('参数错误');
        }
        //奖品名称
        $task['reward_name'] = D('task')->getRewardName($task['reward_type']);
        //奖品汇率
        $rate = explode(':', $task['reward_rate']);
        $task['rate_reward'] = $rate[0];
        $task['rate_promotion'] = $rate[1];
        //任务时限
        $task['task_day'] = floor($task['time_expire'] / (3600 * 24));
        $task['task_hour'] = floor(($task['time_expire'] - $task['task_day'] * 3600 * 24) / 3600);
        $task['task_minute'] = floor(($task['time_expire'] - $task['task_day'] * 3600 * 24 - $task['task_hour'] * 3600) / 60);

        if (empty($task['task_day']))
            $task['task_day'] = '';
        if (empty($task['task_hour']))
            $task['task_hour'] = '';
        if (empty($task['task_minute']))
            $task['task_minute'] = '';
        //起始时间
        $task['time_start'] = $task['time_start'] ? date('Y-m-d H:i:s', $task['time_start']) : '';
        $task['time_end'] = $task['time_end'] ? date('Y-m-d H:i:s', $task['time_end']) : '';

        $task['task_content'] = htmlspecialchars_decode($task['task_content'], ENT_QUOTES);
        $this->assign('task', $task);
        $this->display();
    }

    public function del() {
        $task_id = $this->_postid('id');
        M('task')->update(
                array('is_del' => 1), array('id' => $task_id)
        );
        $this->JsonReturn('删除成功', null, 1);
    }

    /*
     * 任务发布人列表
     */

    public function poster() {
        $where = '';
        if (isset($this->keyword)) {
            $keyword = preg_replace('/\s/', '', $this->keyword);
            $where = " AND p.`poster_name` LIKE '%{$keyword}%' ";
        }

        $sql = "SELECT p.`uid`,p.`poster_name`,p.`task_num`,p.`reg_time`,
				u.`nickname`,u.`phone`
				FROM __PRE__task_poster p,__PRE__user u
				WHERE p.`uid`=u.`uid` $where 
				ORDER BY p.`reg_time` DESC";

        $sql_limit = $sql . " LIMIT {$this->limit},20";
        $poster_list = M()->query($sql_limit);

        $sql_count = "SELECT count(`uid`) total
					  FROM __PRE__task_poster p
					  WHERE 1=1 $where";
        $total = M()->query($sql_count);
        $total = $total[0]['total'];

        $this->assign('total', $total);
        $this->assign('page', $this->page);
        $this->assign('keyword', $this->keyword);
        $this->assign('poster_list', $poster_list);
        $this->display();
    }

    /*
     * 新增任务发布人
     */

    public function add_poster() {
        if (count($_POST)) {
            $uid = $this->_postid('poster_uid');
            //检查重复
            $rs = M('task_poster')
                    ->field('`uid`')
                    ->where(array('uid' => $uid))
                    ->find();
            if ($rs) {
                $this->JsonReturn('已经添加过该用户了', null, 0);
            }
            //是否关注
            $rs = M('user')->field('`uid`')->where(array('uid' => $uid))->find();
            if (!$rs) {
                $this->JsonReturn('该用户尚未关注', null, 0);
            }

            $rs = M('task_poster')->insert(array(
                'uid' => $uid,
                'poster_name' => $this->_post('poster_name'),
                'task_num' => 0,
                'reg_time' => TIME,
            ));
            if ($rs !== false) {
                $this->JsonReturn('添加成功', null, 1);
            } else {
                $this->JsonReturn('添加失败', null, 0);
            }
        }
        $this->display();
    }

    /*
     * ajax根据手机号获取用户信息
     */

    public function get_user() {
        $phone = trim($_POST['phone']);
        if (!preg_match('/^1[3-8]\d{9}$/', $phone)) {
            $this->JsonReturn('手机号格式不正确', null, 0);
        }
        $rs = M('user')
                ->field('`uid`,`nickname`')
                ->where(array('phone' => $phone))
                ->find();
        if ($rs) {
            $this->JsonReturn($rs, null, 1);
        } else {
            $this->JsonReturn('手机号尚未注册', null, 0);
        }
    }

    /*
     * 活动参与用户列表
     */

    public function statistic() {
        $task_id = $this->_getid('id');

        $where = " `task_id`={$task_id} ";
        if (isset($_GET['reward'])) {
            $where .= " AND `reward_get`>0 ";
        }

        $limit = "";
        if (!isset($_GET['export'])) {
            $limit = "{$this->limit},20";
        }

        $user_list = M('task_statistic')
                ->field('`task_id`,`uid`,`reward_get`,`time_add`,`promotion_time`,`promotion_code`')
                ->where($where)
                ->order('`time_add` DESC')
                ->limit($limit)
                ->findAll();

        $total = D('task_statistic')->getTotal();

        $uid_arr = array();
        foreach ($user_list as $v) {
            $uid_arr[] = $v['uid'];
        }
        $uids = implode(',', $uid_arr);
        if (empty($uids))
            $uids = 0;
        $nickname = M('user')
                ->field('`uid`,`nickname`')
                ->where("`uid` in ($uids)")
                ->findAll(false);
        $temp_arr = array();
        foreach ($nickname as $v) {
            $temp_arr[$v['uid']] = $v['nickname'];
        }

        foreach ($user_list as $k => $v) {
            $user_list[$k]['nickname'] = empty($temp_arr[$v['uid']]) ? '' : $temp_arr[$v['uid']];
            $user_list[$k]['time_add'] = $v['time_add'] ? date('Y-m-d H:i:s', $v['time_add']) : '';
        }

        if (isset($_GET['export'])) {
            $this->export_statistic($user_list);
            exit;
        }

        $this->assign('task_id', $task_id);
        $this->assign('page', $this->page);
        $this->assign('total', $total);
        $this->assign('user_list', $user_list);
        $this->display();
    }

    /*
     * 导出中奖名单
     */

    private function export_statistic($data) {
        $title = array(
            "UID", "昵称", "分享次数", "奖励数量", //"分享码"
        );

        $_data = array();

        if ($data) {
            foreach ($data as $k => $v) {
                $_data[] = array(
                    'uid' => $v['uid'],
                    'nickname' => $v['nickname'],
                    'promotion_time' => $v['promotion_time'],
                    'reward_get' => $v['reward_get'],
                        //'promotion_code' => $v['promotion_code'],
                );
            }
        }

        load('csv');
        $csv = new csv();
        $csv->write($title, $_data, "中奖名单" . date('Y-m-d H/i/s'));
    }

    /*
     * 用户列表
     */

    public function user() {
        $user_list = M('task_user')
                ->field('`uid`,`task_total`,`reward_credit`,`reward_coin`,`reg_time`,`state`')
                ->where("1=1")
                ->order('`reg_time` DESC')
                ->limit("{$this->limit},20")
                ->findAll();
        $total = M('task_user')->field('uid')->where("1=1")->findAll();
        $total = count($total);

        $uid_arr = array();
        foreach ($user_list as $v) {
            $uid_arr[] = $v['uid'];
        }
        $uids = implode(',', $uid_arr);
        if (empty($uids))
            $uids = 0;
        $nickname = M('user')
                ->field('`uid`,`nickname`')
                ->where("`uid` in ($uids)")
                ->findAll();
        $temp_arr = array();
        foreach ($nickname as $v) {
            $temp_arr[$v['uid']] = $v['nickname'];
        }

        foreach ($user_list as $k => $v) {
            $user_list[$k]['nickname'] = $temp_arr[$v['uid']];
            $user_list[$k]['reg_time'] = $v['reg_time'] ? date('Y-m-d H:i:s', $v['reg_time']) : '';
            $user_list[$k]['status'] = $v['state'] ? '正常' : '<span class="red">冻结</span>';
        }

        $this->assign('page', $this->page);
        $this->assign('total', $total);
        $this->assign('user_list', $user_list);
        $this->display();
    }

    /*
     * 改变用户状态 冻结or解冻
     */

    public function change_state() {
        $uid = $this->_postid('uid');
        $rs = M('task_user')
                ->field('`state`')
                ->where(array('uid' => $uid))
                ->find();
        $state = $rs['state'] ? 0 : 1;
        M('task_user')->update(
                array('state' => $state), array('uid' => $uid)
        );
        $this->JsonReturn('ok', $state, 1);
    }

    /*
     * 处理表单输入
     */

    private function _input() {
        $tablefields = M('task')->getTableFields();
        $data = array();
        foreach ($tablefields['fields'] as $key => $value) {
            if (!isset($_POST[$key]))
                continue;
            if (is_string($this->_post($key))) {
                $data[$key] = trim($this->_post($key));
            }
        }

        //奖品汇率
        $num_reward = $this->_postid('rate_reward');
        $num_promotion = $this->_postid('rate_promotion');
        $data['reward_rate'] = $num_reward . ':' . $num_promotion;
        //任务时限
        $task_day = $this->_postid('task_day');
        $task_hour = $this->_postid('task_hour');
        $task_minute = $this->_postid('task_minute');
        $data['time_expire'] = $task_day * 3600 * 24 + $task_hour * 3600 + $task_minute * 60;
        //起始时间
        $data['time_start'] = strtotime($this->_post('time_start'));
        $data['time_end'] = strtotime($this->_post('time_end'));
        //任务详情
        $data['task_content'] = html_entity_decode(htmlspecialchars_decode($_POST['task_content'], ENT_NOQUOTES));

        return $data;
    }

    /*
     * 活动列表
     */

    public function event() {
        $event_list = M('task_event')
                ->field('`id`,`time_start`,`time_end`,`event_title`,`event_banner`,`event_link`,`is_hidden`')
                ->where('1=1')
                ->order('`event_sort`,`event_add` DESC')
                ->limit("{$this->limit},20")
                ->findAll();

        foreach ($event_list as $k => $v) {
            $event_list[$k]['time_start'] = empty($v['time_start']) ? '' : date('Y-m-d H:i:s', $v['time_start']);
            $event_list[$k]['time_end'] = empty($v['time_end']) ? '' : date('Y-m-d H:i:s', $v['time_end']);
            if ($v['time_start'] > TIME) {
                $event_list[$k]['status'] = '未上线';
            } else if ($v['time_start'] <= TIME && $v['time_end'] >= TIME) {
                $event_list[$k]['status'] = '展示中';
            } else {
                $event_list[$k]['status'] = '已下线';
            }
        }

        // $total = M('task_event')->field('`id`')->findAll();
        // $total = count($total);
        $total = M('task_event')->getTotal();

        $this->assign('page', $this->page);
        $this->assign('total', $total);
        $this->assign('event_list', $event_list);
        $this->display();
    }

    /*
     * 新增活动
     */

    public function add_event() {
        if (count($_POST)) {
            $data = $this->_event_input();
            $data['event_add'] = TIME;

            $rs = M('task_event')->insert($data);
            if ($rs > 0) {
                $this->JsonReturn('添加成功', $rs, 1);
            } else {
                $this->JsonReturn($rs, null, 0);
            }
        }
        $this->display();
    }

    /*
     * 编辑活动
     */

    public function edit_event() {
        if (count($_POST)) {
            $id = $this->_postid('id');
            $data = $this->_event_input();

            M('task_event')->update(
                    $data, array('id' => $id)
            );
            $this->JsonReturn('编辑成功', $id, 1);
        }

        $id = $this->_getid('id');
        $rs = M('task_event')
                ->field('`id`,`event_id`,`event_title`,`event_banner`,`event_link`,`time_start`,`time_end`,`event_sort`')
                ->where(array('id' => $id))
                ->find();

        if (empty($rs)) {
            showError('活动参数错误');
        }
        $rs['time_start'] = date('Y-m-d H:i:s', $rs['time_start']);
        $rs['time_end'] = date('Y-m-d H:i:s', $rs['time_end']);

        $this->assign('event', $rs);
        $this->display();
    }

    /*
     * 隐藏/显示活动
     */

    public function change_event() {
        $id = $this->_postid('id');
        $rs = M('task_event')->update(
                "`is_hidden`=-`is_hidden`", array('id' => $id)
        );

        $this->JsonReturn('ok', null, 1);
    }

    private function _event_input() {
        $data = array();
        $data['event_title'] = $this->_post('event_title');
        $data['event_id'] = $this->_post('event_id');
        $data['event_banner'] = $this->_post('event_banner');
        $data['event_link'] = $this->_post('event_link');
        $data['event_sort'] = $this->_post('event_sort');
        $data['time_start'] = strtotime($this->_post('time_start'));
        $data['time_end'] = strtotime($this->_post('time_end'));

        if (strpos($data['event_link'], 'http://') === false) {
            $data['event_link'] = 'http://' . $data['event_link'];
        }

        return $data;
    }

    function upload() {
        if (parent::_checkLogin(true)) {
            load('upload');
            $myUpload = new Myupload();
            $upload = $myUpload->upload('task/u' . admin::$adminInfo['aid']);
            $upload = parent::_sendImageToYunServer($upload); //同步图片到云存储
            if ($upload) {
                $upload = $upload[0];
                if (!$upload) {
                    echo json_encode(array('url' => '', 'fileType' => '', 'original' => '', 'state' => $myUpload->getErrorMsg()));
                } else {
                    echo json_encode(array('url' => getImgUrl($upload['savepath']), 'fileType' => $upload['type'], 'original' => $upload['realname'], 'state' => 'SUCCESS'));
                }
            }
        } else {
            echo json_encode(array('url' => '', 'fileType' => '', 'original' => '', 'state' => '上传失败'));
            exit;
        }
    }

}
